在程式語言中,「變數」就像是一個能裝資料的小盒子,你可以把東西放進去、改掉、或拿出來用。
name = "Chloe"
age = 20
height = 168
is_student = True
說明:
變數名稱 | 資料型態 | 資料內容 |
---|---|---|
name |
字串 | "Chloe" |
age |
整數 | 20 |
height |
浮點數 | 168 |
is_student |
布林值 | True |
類型 | 範例 | 說明 |
---|---|---|
整數 int | 10 |
沒有小數點的數字 |
浮點 float | 3.14 |
有小數點的數字 |
字串 str | "Hello" |
一串文字,用 "" 包起來 |
布林 bool | True / False |
表示是或否、真或假 |
name = "Chloe"
age = 20
height = 168
is_student = True
print("My name is", name)
print("I am", age, "years old.")
print("My height is", height, "cm.")
print("Identity_student:", is_student)
score = 85
print('成績:', score)
score = score + 5
print('調整後成績:', score)
今天我學會了如何使用「變數」來儲存資料,程式不再只是單純地印出一句話,而是可以「記住」一些資訊並進行運算。
一開始我寫了一段程式想輸出成績:
score = 85
print("成績:" + score)
結果卻出現錯誤訊息:
TypeError: can only concatenate str (not "int") to str
才發現原來 Python 不像 Java 可以自動把整數接在字串後面,必須手動轉成字串(例如 str(score)),或使用逗號分隔、f-string 等方式。這個錯誤讓我更清楚地理解了 Python 對資料型別轉換的要求,也提醒我下次在輸出變數時要更細心。而我也另外學會了f-string的寫法:
score = 85
print(f'成績:{score}')
score += 5
print(f'調整後成績:{score}')
我覺得程式有趣的地方,卻也是我當初學 Java 最難理解的,就是「同一種情境可以有多種寫法」。我也不曾真正理解他們每個寫法的意義是甚麼。然而我藉由這次的錯誤,了解在python中用逗號分隔方式會自動幫忙做型別得轉換。而手動使用 str() 轉換則可以幫助我們更清楚掌握目前的資料型態,也有助於未來除錯與理解程式邏輯。
明天我會繼續學習 input() 的使用方式,讓程式不再只是我對電腦說話,而是能和使用者互動,根據輸入內容做出不同反應,讓程式更有溫度與智慧!